package com.winsafe.scanlibrary.base;

import android.os.Handler;
import android.os.Message;

import androidx.fragment.app.Fragment;

import com.winsafe.scanlibrary.HoneywellScanResultReceiver;
import com.winsafe.scanlibrary.HoneywellScanner;
import com.winsafe.scanlibrary.IDataScanner;
import com.winsafe.scanlibrary.NewlandScanner;
import com.winsafe.scanlibrary.ScanResultReceiver;
import com.winsafe.scanlibrary.SeuicScanner;
import com.winsafe.scanlibrary.UrovoScanner;

public abstract class BaseScanFragment extends Fragment {

    @Override
    public void onResume() {
        super.onResume();
        try {
            registerScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            unregisterScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫描注册
     * onResume
     */
    protected void registerScan() {

        //Honeywell
        HoneywellScanner.mHandler = mHandler;
        HoneywellScanner.registerBroadcastReceiver();
        HoneywellScanner.startScanner();

        //iData
        IDataScanner.mHandler = mHandler;
        IDataScanner.registerBroadcastReceiver();
        //Seuic 东集
        SeuicScanner.mHandler = mHandler;
        SeuicScanner.registerSeuicBroadcastReceiver();
        //Newland
        NewlandScanner.mHandler = mHandler;
        NewlandScanner.registerBroadcastReceiver();
        //优博讯
        UrovoScanner.mHandler = mHandler;
        UrovoScanner.registerBroadcastReceiver();

    }

    /**
     * 解绑扫描
     * onPause
     */
    protected void unregisterScan() {

        //Honeywell
        HoneywellScanner.unregisterBroadcastReceiver();
        HoneywellScanner.stopScanner();

        //iData
        IDataScanner.unregisterBroadcastReceiver();
        //Seuic 东集
        SeuicScanner.unregisterSeuicBroadcastReceiver();
        //iData
        NewlandScanner.unregisterBroadcastReceiver();
        //优博讯
        UrovoScanner.unregisterBroadcastReceiver();
    }

    /**
     * 获取数据
     */
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {

            switch (message.what) {
                case HoneywellScanResultReceiver.READ_RESULT:
                case ScanResultReceiver.READ_RESULT:
                    String result = (String) message.obj;
                    onScanResult(result);
                    break;
            }
            return false;
        }
    });

    /**
     * 扫码结果，如果页面不需要，在实现后，不做处理即可
     *
     * @param idCode
     */
    protected abstract void onScanResult(String idCode);
}
